package com.wfh.mianshiji.ai.agent;

import com.wfh.mianshiji.ai.advisor.MyLoggerAdvisor;
import com.wfh.mianshiji.ai.chatmemory.InterviewDbChatMemory;
import com.wfh.mianshiji.ai.chatmemory.InterviewRedisChatMemory;
import com.wfh.mianshiji.ai.rag.RagCustomAdvisorFactory;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

/**
 * @Title: InterviewAgent
 * @Author wangfenghuan
 * @Package com.wfh.mianshiji.ai.agent
 * @Date 2025/10/31 18:43
 * @description:
 */
@Component
@Scope("prototype") // 设置成多例的bean，
public class InterviewAgent {

    private final ChatClient chatClient;

    @Resource
    private VectorStore pgVectorVectorStore;


    public InterviewAgent(
            @Qualifier("openAiChatModel") ChatModel chatModel,
           InterviewRedisChatMemory interviewRedisChatMemory) { // ← 直接通过构造函数注入
        ClassPathResource fileSystemResource = new ClassPathResource("prompt/interview.txt");
        this.chatClient = ChatClient.builder(chatModel)
                .defaultSystem(fileSystemResource)
                .defaultAdvisors(
                        MessageChatMemoryAdvisor.builder(interviewRedisChatMemory).build(),
                        new MyLoggerAdvisor()
                )
                .build();
    }

    /**
     * RAG流式对话
     * @param message
     * @param interviewId
     * @return
     */
    public Flux<String> doChatStream(String message, String interviewId) {
        // 开启日志
        Flux<String> content = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, interviewId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 50))
                // MyLoggerAdvisor已经在defaultAdvisors中添加，这里不再重复添加
                // .advisors(new MyLoggerAdvisor())
                // 暂时关闭rag向量检索，避免干扰面试对话
                // .advisors(RagCustomAdvisorFactory.createRagAdvisor(pgVectorVectorStore, "Java"))
                .stream().content();
        return content;
    }

}
